﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BusinessObjects;
using BusinessLogic;
using DCMSExceptions;

namespace Presentation.Children {
  /// <summary>
  /// Kinderfiche form
  /// </summary>
  public partial class ContractsForm : Form {

    private ChildrenBll bll = new ChildrenBll( );
    private BusinessObjects.Children children = new BusinessObjects.Children( );
    private BusinessObjects.Children originalList = new BusinessObjects.Children( );
    private Child currentChild;
    private bool allChildren;

    #region - Constructor -

    /// <summary>
    /// Initializes a new instance of the <see cref="ContractsForm"/> class.
    /// </summary>
    public ContractsForm( ) {
      InitializeComponent( );
      stateLabel.Text = string.Empty;

      childFicheControl.weekRadioButton.CheckedChanged += new EventHandler( radioButton_CheckedChanged );
      childFicheControl.twoWeekRadioButton.CheckedChanged += new EventHandler( radioButton_CheckedChanged );
      childFicheControl.monthRadioButton.CheckedChanged += new EventHandler( radioButton_CheckedChanged );
      childFicheControl.variableRadioButton.CheckedChanged += new EventHandler( radioButton_CheckedChanged );
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="ContractsForm"/> class.
    /// </summary>
    /// <param name="childrensList">The childrens list.</param>
    /// <param name="selectedChild">The selected child.</param>
    /// <param name="allChildren">if set to <c>true</c> [all children].</param>
    public ContractsForm( BusinessObjects.Children childrensList, int selectedChild, bool allChildren )
      : this( ) {
      this.allChildren = allChildren;
      children = childrensList;
      childrenBindingSource.DataSource = children;
      childFicheNavigator.BindingSource = childrenBindingSource;

      this.childFicheControl.ControlBindingSource = childrenBindingSource;
      this.childFicheControl.motherFicheControl.ControlBindingSource = childrenBindingSource;
      this.childFicheControl.fatherFicheControl.ControlBindingSource = childrenBindingSource;

      childrenBindingSource.Position = selectedChild;
    }


    #endregion

    #region - Events -

    private void ContractsForm_Load( object sender, EventArgs e ) {
      foreach ( Child child in children ) {
        Child copy = child.Copy( );
        originalList.Add( copy );
      }
      SetCurrentChild( );
    }

    private void bindingNavigatorMoveFirstItem_Click( object sender, EventArgs e ) {
      Navigate( PresentationHelper.BindingNavigatorMoveType.First );
      SetCurrentChild( );
    }

    private void bindingNavigatorMovePreviousItem_Click( object sender, EventArgs e ) {
      Navigate( PresentationHelper.BindingNavigatorMoveType.Previous );
      SetCurrentChild( );
    }

    private void bindingNavigatorMoveNextItem_Click( object sender, EventArgs e ) {
      Navigate( PresentationHelper.BindingNavigatorMoveType.Next );
      SetCurrentChild( );
    }

    private void bindingNavigatorMoveLastItem_Click( object sender, EventArgs e ) {
      Navigate( PresentationHelper.BindingNavigatorMoveType.Last );
      SetCurrentChild( );
    }

    private void saveButton_Click( object sender, EventArgs e ) {
      Save( );
    }

    private void searchButton_Click( object sender, EventArgs e ) {
      ChildrenListForm listForm = new ChildrenListForm( );
      if ( listForm.ShowDialog( ) == System.Windows.Forms.DialogResult.OK ) {

        children = listForm.Children;
        childrenBindingSource.DataSource = children;
        childrenBindingSource.Position = listForm.SelectedPosition;

        this.childFicheControl.ControlBindingSource = childrenBindingSource;
        this.childFicheControl.motherFicheControl.ControlBindingSource = childrenBindingSource;
        this.childFicheControl.fatherFicheControl.ControlBindingSource = childrenBindingSource;
        SetCurrentChild( );
      }
    }

    private void undoButton_Click( object sender, EventArgs e ) {
      UndoChanges( );
    }

    private void refreshButton_Click( object sender, EventArgs e ) {

      if ( TrySave( ) != null && !currentChild.IsNew ) {
        children.Clear( );
        originalList.Clear( );
        children = bll.GetChildren( this.allChildren );
        foreach ( Child child in children ) {
          Child copy = child.Copy( );
          originalList.Add( copy );
        }
        ReBindChildren( );
      }
    }

    private void deleteButton_Click( object sender, EventArgs e ) {
      try {
        bll.Delete( currentChild );
      } catch ( BusinessException ex ) {
        MessageBox.Show( ex.Message, "Verwijderen niet mogelijk", MessageBoxButtons.OK, MessageBoxIcon.Warning );
      }
    }

    private void childrenBindingSource_CurrentItemChanged( object sender, EventArgs e ) {
      currentChild = ( Child ) childrenBindingSource.Current;
      if ( currentChild != null ) {
        stateLabel.Image = PresentationHelper.ImageStateList.Images[ Convert.ToInt32( currentChild.ChildActiveState ) ];

        switch ( currentChild.Schedule.Type ) {
          case Schedule.ScheduleType.Weekly:
            childFicheControl.weekRadioButton.Checked = true;
            break;
          case Schedule.ScheduleType.Twoweekly:
            childFicheControl.twoWeekRadioButton.Checked = true;
            break;
          case Schedule.ScheduleType.Monthly:
            childFicheControl.monthRadioButton.Checked = true;
            break;
          case Schedule.ScheduleType.Variable:
            childFicheControl.variableRadioButton.Checked = true;
            break;
          default:
            break;
        }
      }
    }

    private void radioButton_CheckedChanged( object sender, EventArgs e ) {
      RadioButton radioButton = ( RadioButton ) sender;
      Child current = ( Child ) childrenBindingSource.Current;

      if ( current != null ) {

        if ( radioButton.Name.Equals( childFicheControl.weekRadioButton.Name ) ) {
          if ( radioButton.Checked ) {
            current.Schedule.Type = Schedule.ScheduleType.Weekly;
          }
        } else if ( radioButton.Name.Equals( childFicheControl.twoWeekRadioButton.Name ) ) {
          if ( radioButton.Checked ) {
            current.Schedule.Type = Schedule.ScheduleType.Twoweekly;
          }
        } else if ( radioButton.Name.Equals( childFicheControl.monthRadioButton.Name ) ) {
          if ( radioButton.Checked ) {
            current.Schedule.Type = Schedule.ScheduleType.Monthly;
          }
        } else if ( radioButton.Name.Equals( childFicheControl.variableRadioButton.Name ) ) {
          if ( radioButton.Checked ) {
            current.Schedule.Type = Schedule.ScheduleType.Variable;
          }
        }
        //SetCurrentChild( );
        childFicheControl.SetScheduleTypeView( current.Schedule.Type );
      }
    }

    private void ContractsForm_FormClosing( object sender, FormClosingEventArgs e ) {
      bool? saved = TrySave( );
      if ( saved == null ) {
        e.Cancel = true;
      } else if ( saved == false ) {
        e.Cancel = false;
      }
    }

    #endregion

    #region - Methods -

    private void Navigate( PresentationHelper.BindingNavigatorMoveType navi ) {
      if ( TrySave( ) != null ) {
        PresentationHelper.MoveBinding( this.childrenBindingSource, navi );
      }
    }

    private void UndoChanges( ) {
      ClearAllErrorProviders( );

      for ( int i = 0; i < originalList.Count; i++ ) {
        if ( currentChild.Id.Equals( originalList[ i ].Id ) ) {
          currentChild = originalList[ i ].Copy( );
          break;
        }
      }

      for ( int i = 0; i < children.Count; i++ ) {
        if ( currentChild.Id.Equals( children[ i ].Id ) ) {
          children[ i ] = currentChild.Copy( );
          break;
        }
      }

      ReBindChildren( );
    }

    private void ClearAllErrorProviders( ) {
      childFicheControl.childficheErrorProvider.Clear( );
      childFicheControl.motherFicheControl.parentErrorProvider.Clear( );
      childFicheControl.scheduleErrorProvider.Clear( );
    }

    private bool? TrySave( ) {
      bool? saved = null;
      if ( currentChild != null && currentChild.HasChanged ) {
        DialogResult result = MessageBox.Show( "Wijzigingen bewaren?", "Wijzigingen", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question );
        if ( result == DialogResult.Yes ) {
          saved = Save( );
        } else if ( result == DialogResult.No ) {
          UndoChanges( );
          saved = false;
        }
      } else {
        saved = false;
      }
      return saved;
    }

    private bool? Save( ) {
      bool? saved = null;
      try {

        int selectedPage = childFicheControl.childFicheTabControl.SelectedIndex;
        for ( int i = 0; i < childFicheControl.childFicheTabControl.TabPages.Count - 1; i++ ) {
          childFicheControl.childFicheTabControl.SelectedIndex = i;
        }
        childFicheControl.childFicheTabControl.SelectedIndex = selectedPage;

        if ( ValidateChildren( ) ) {
          bll.SaveChild( currentChild );

          for ( int i = 0; i < originalList.Count; i++ ) {
            if ( currentChild.Id.Equals( originalList[ i ].Id ) ) {
              originalList[ i ] = currentChild.Copy( );
              break;
            }
          }
          saved = true;
        } else {

          if ( childFicheControl.childficheErrorProvider.HasErrors ) {
            foreach ( Control ctrl in childFicheControl.childficheErrorProvider.ControlList ) {
              if ( ctrl.Parent == childFicheControl.childFicheTabControl.TabPages[ "financialPage" ] ) {
                childFicheControl.childFicheTabControl.SelectedTab = childFicheControl.childFicheTabControl.TabPages[ "financialPage" ];
              } else if ( ctrl.Parent == childFicheControl.childFicheTabControl.TabPages[ "schemaPage" ] ) {
                childFicheControl.childFicheTabControl.SelectedTab = childFicheControl.childFicheTabControl.TabPages[ "schemaPage" ];
              } else {
                childFicheControl.childFicheTabControl.SelectedIndex = 0;
              }
              break;
            }
          } else if ( childFicheControl.motherFicheControl.parentErrorProvider.HasErrors ) {
            childFicheControl.childFicheTabControl.SelectedIndex = 1;
          } else if ( childFicheControl.fatherFicheControl.parentErrorProvider.HasErrors ) {
            childFicheControl.childFicheTabControl.SelectedIndex = 2;
          } else if ( childFicheControl.scheduleErrorProvider.HasErrors ) {
            childFicheControl.childFicheTabControl.SelectedIndex = 3;
          }
          saved = null;
        }
      } catch ( DCMSExceptions.BusinessException ex ) {
        MessageBox.Show( "Fout bij bewaren.\n" + ex.Message, "Bewaarfout", MessageBoxButtons.OK, MessageBoxIcon.Error );
      }
      return saved;
    }

    private void SetCurrentChild( ) {

      currentChild = ( Child ) childrenBindingSource.Current;
      currentChild.MarkClean( );

      childFicheControl.CurrentChild = currentChild;
      childFicheControl.motherFicheControl.CurrentChild = currentChild;
      childFicheControl.fatherFicheControl.CurrentChild = currentChild;
      childFicheControl.trustPersonBindingSource.DataSource = currentChild.TrustPersons;
      childFicheControl.trustPersonGridView.DataSource = childFicheControl.trustPersonBindingSource;

      if ( currentChild.Link == 0 ) {
        childFicheControl.linkButton.Image = Properties.Resources.LinkBreak16;
      } else {
        childFicheControl.linkButton.Image = Properties.Resources.Link16;
      }

    }

    private void ReBindChildren( ) {
      int position = childrenBindingSource.Position;
      childrenBindingSource.DataSource = typeof( Child );
      childrenBindingSource.DataSource = children;
      childFicheControl.ControlBindingSource.DataSource = typeof( Child );
      childFicheControl.ControlBindingSource.DataSource = children;
      childFicheControl.motherFicheControl.ControlBindingSource.DataSource = typeof( Child );
      childFicheControl.motherFicheControl.ControlBindingSource.DataSource = children;
      childFicheControl.fatherFicheControl.ControlBindingSource.DataSource = typeof( Child );
      childFicheControl.fatherFicheControl.ControlBindingSource.DataSource = children;
      childrenBindingSource.Position = position;
    }

    #endregion

  }
}
